#import "MRQRCode.h"

@implementation MRQRCode

+ (id)qrcodeWithHandler:(QRCodeHandler)handler
{
	MRQRCode *code = [[MRQRCode alloc] init];
	code.hidesBottomBarWhenPushed = YES;
	code->_handler = handler;
	
	return code;
}

- (void)viewDidLoad
{
	[super viewDidLoad];
	self.navigationItem.title = L(@"SCAN_QRCODE");
	
	//Device
	_device = [AVCaptureDevice defaultDeviceWithMediaType:AVMediaTypeVideo];
	
	//Input
	_input = [AVCaptureDeviceInput deviceInputWithDevice:_device error:nil];
	
	//Output
	_output = [[AVCaptureMetadataOutput alloc] init];
	[_output setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
	
	//Session
	_session = [[AVCaptureSession alloc] init];
	[_session setSessionPreset:AVCaptureSessionPreset1280x720];
	if ([_session canAddInput:_input]) [_session addInput:_input];
	if ([_session canAddOutput:_output]) [_session addOutput:_output];
	
	//条码类型 AVMetadataObjectTypeQRCode
	if (_output.availableMetadataObjectTypes.count)
		_output.metadataObjectTypes = @[AVMetadataObjectTypeQRCode, AVMetadataObjectTypeEAN13Code, AVMetadataObjectTypeEAN8Code, AVMetadataObjectTypeCode128Code, AVMetadataObjectTypeUPCECode];
	else
		[MRAlert alertWithMessage:NSLocalized(@"IDS_DISCAMERA")];
	
	//Preview
	_preview = [AVCaptureVideoPreviewLayer layerWithSession:_session];
	_preview.videoGravity = AVLayerVideoGravityResizeAspectFill;
	
	if (_preview.connection.isVideoOrientationSupported)
	{
		_preview.connection.videoOrientation = (AVCaptureVideoOrientation)[[UIApplication sharedApplication] statusBarOrientation];
	}
	[self.view.layer insertSublayer:_preview atIndex:0];

	//扫描线
	_lineView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"saomiaotiao"]];
	_lineView.layer.opacity = 0;
	_lineView.layer.speed = 0;
	[self.view addSubview:_lineView];
	
//	if (IOS8)
//	{
//		_userView = [[UINavigationBar alloc] init];
//		((UINavigationBar *)_userView).delegate = self;
//	}
//	else	//IOS7无法对UINavigationBar进行Mask
//	{
		_userView = [[UIView alloc] init];
		_userView.backgroundColor = rgba(0, 0, 0, .6);
//	}
	[_userView addConstraintEqualSuperview:self.view];
    
}

/*===================================================================
 说明:
	初始化
 ==================================================================*/
- (void)viewWillCreate
{
	CGFloat w = LOCPIXEL(self.view.bounds.size.width * .68);
	CGRect rect = CGRectMake((self.view.bounds.size.width - w) / 2, (self.view.bounds.size.height - w) / 2, w, w);
	
	if (self.navigationController.viewControllers.firstObject == self)
	{
		self.navigationItem.leftBarButtonItem = [UIBarButtonItem initBackWithTitle:NSLocalized(@"IDS_CANCEL") target:self action:@selector(cancel) image:nil];
	}
	
	_preview.frame = self.view.bounds;
	self.path = [UIBezierPath bezierPathWithRoundedRect:rect cornerRadius:DPISCALE(0)];
}

- (void)viewWillDealloc
{
	if (_session.isRunning)
	{
		[self stopScan];
		[_lineView.layer removeAllAnimations];
		_handler = nil;
	}
	[super viewWillDealloc];
}

/*===================================================================
 说明:
	旋转方向
 ==================================================================*/
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
	[super willRotateToInterfaceOrientation:toInterfaceOrientation duration:duration];
	
	if (_preview.connection.isVideoOrientationSupported)
	{
		_preview.connection.videoOrientation = (AVCaptureVideoOrientation)toInterfaceOrientation;
	}
}

/*===================================================================
 说明:
	配置遮罩层图像
 ==================================================================*/
- (void)setPath:(UIBezierPath *)path
{
	_path = path;
	CGRect rect = CGPathGetBoundingBox(_path.CGPath);
//	
//	CAShapeLayer *layer = [CAShapeLayer layer];
//	layer.frame = self.view.bounds;
//	layer.fillColor = [UIColor clearColor].CGColor;
//	layer.strokeColor = [UIColor whiteColor].CGColor;
//	layer.lineWidth = 1;
//	layer.lineDashPattern = @[@(LOCPIXEL(7)), @(LOCPIXEL(7))];
//	layer.path = path.CGPath;
//	
//	[_userView.layer addSublayer:layer];
    
    UIImageView *borderImg = [[UIImageView alloc] initWithFrame:rect];
    borderImg.image = [UIImage imageNamed:@"saomiaokuan"];
    [self.view addSubview: borderImg];
    
    CGRect labelRect = CGRectMake(rect.origin.x, rect.origin.y+rect.size.height+15, rect.size.width, 40);
    UILabel *tipsLab = [[UILabel alloc] initWithFrame:labelRect];
    tipsLab.text = L(@"SCAN_NOTE");
    tipsLab.font = [UIFont fontWithName:@"PingFang SC" size:14];
    tipsLab.textAlignment = NSTextAlignmentCenter;
    tipsLab.textColor = [UIColor whiteColor];
    tipsLab.numberOfLines = 2;
    [self.view addSubview:tipsLab];
	
	UIBezierPath *border = [UIBezierPath bezierPathWithRect:self.view.bounds];
	[border appendPath:_path];
	
	CAShapeLayer *mask = [CAShapeLayer layer];
	mask.frame = self.view.bounds;
	mask.path = border.CGPath;
	mask.fillColor = [UIColor blackColor].CGColor;
	mask.fillRule = kCAFillRuleEvenOdd;
	
	//扫描线
	_userView.layer.mask = mask;
	_lineView.frame = CGRectMake(rect.origin.x + 5, rect.origin.y, rect.size.width - 10, 1);
	
	CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
	animation.repeatCount = INFINITY;
	animation.removedOnCompletion = NO;
	animation.duration = 3;
	animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear];
	
	animation.values = @[[NSValue valueWithCATransform3D:CATransform3DIdentity],
						 [NSValue valueWithCATransform3D:CATransform3DMakeTranslation(0, rect.size.height, 0)]];
	
	[_lineView.layer addAnimation:animation forKey:nil];
	
	//解析区域
	CGSize size = self.view.bounds.size;
	_output.rectOfInterest = CGRectMake(rect.origin.y / size.height, rect.origin.x / size.width, rect.size.height / size.height, rect.size.width / size.width);
}

/*===================================================================
 说明:
	开始扫描
 ==================================================================*/
- (void)viewDidPushed:(BOOL)animated
{
	[self startScan];
}

#pragma mark - 扫描
/*===================================================================
 说明:
	扫描
 ==================================================================*/
- (void)startScan
{
	if ([_session isRunning]) return;
	
	[_session startRunning];
	
	_lineView.layer.speed = 1;
	_lineView.layer.opacity = 1;
}

- (void)stopScan
{
	[_session stopRunning];
	
	_lineView.layer.speed = 0;
	_lineView.layer.opacity = 0;
}

/*===================================================================
 说明:
	扫描成功
 ==================================================================*/
- (void)captureOutput:(AVCaptureOutput *)captureOutput didOutputMetadataObjects:(NSArray *)metadataObjects fromConnection:(AVCaptureConnection *)connection
{
	if (metadataObjects.count)
	{
		[self stopScan];
		
		//扫描成功声音
		NSString *path = [[NSBundle mainBundle] pathForResource:@"qrcode" ofType:@"wav"];
		if (path)
		{
			__block SystemSoundID soundID;
			AudioServicesCreateSystemSoundID((__bridge CFURLRef)[NSURL fileURLWithPath:path], &soundID);
			AudioServicesPlaySystemSound(soundID);
		}
		
		__weak id this = self;
		if (_handler) _handler(this, metadataObjects.firstObject);
	}
}

@end
